import { useCallback, useEffect, useState } from 'react';
import { Button, Popup, Space, TreeSelect } from 'antd-mobile';
import { useParams } from 'react-router-dom';
import { InbizIcon, tranferIcon, h5Utils as Core } from '@inbiz/utils';
import { useInbizRouter } from '@inbiz/hooks';
import { TextWidget } from '@inbiz/react';
import { menuTreeList } from './servers';
import './index.less';

interface PopupMenuProps {
  titleOption: {
    status: boolean;
    value: string;
  };
  iconOption: {
    type: string;
    size: number;
    color: string;
  };
  textColor: string;
  bgColor: string;
  fontSize: number;
  position: 'left' | 'right';
  className?: string;
  inbiz?: any;
}

const PopupMenu = (props: PopupMenuProps) => {
  // popup抽屉显示控制
  const [visible, $visible] = useState<boolean>(false);
  // 菜单数据
  const [menuTree, $menuTree] = useState<any[]>([]);
  // 当前路由节点
  const [defaultValue, $defaultValue] = useState<string[]>([]);
  // 当前路由数据（会随路由变化而触发变化）
  const params: any = useParams();

  // 配置信息
  const { titleOption, iconOption, fontSize, textColor, bgColor, position, className, inbiz } =
    props;
  // 站点信息
  const appInfo = inbiz.appInfo;
  // 图标数据
  const { type, color, size } = iconOption;
  // 文本数据
  const { value, status } = titleOption;

  const history = useInbizRouter();


  // 初始化
  useEffect(() => {
    getMenuTreeList();
  }, []);

  // 获取菜单数据
  const getMenuTreeList = useCallback(async () => {
    let res = await menuTreeList({
      siteOutId: appInfo.OutId,
      appId: appInfo.AppId,
      dataVersionId: appInfo.DataVersionId,
    });
    if (!res || res.error) {
      return;
    }
    if (res.length > 0) {
      transferTree(res);
    }
  }, []);

  // 组织二级菜单数据
  const transferData = useCallback((data: any, route: string) => {
    let node: any = [];
    if (Array.isArray(data) && data.length) {
      data.forEach((item: any) => {
        let icon: any = tranferIcon(item.Icon);
        item.oldRoute = item.Route;
        item.Route = `${route}/${item.Route}`;
        node.push({
          label: (
            <div key={item.OutId}>
              {icon?.type ? (
                <InbizIcon type={icon.type} style={{ fontSize: 16, marginRight: 5 }} />
              ) : null}
              <TextWidget>{item.DisplayName}</TextWidget>
            </div>
          ),
          value: item.OutId,
          menu: item,
        });
      });
    }
    return node;
  }, []);

  // 整理菜单数据
  const transferTree = useCallback((data: any[]) => {
    let tree: any[] = [];
    data.forEach((item) => {
      let icon: any = tranferIcon(item.Icon);
      tree.push({
        label: (
          <div key={item.OutId}>
            {icon?.type ? (
              <InbizIcon type={icon.type} style={{ fontSize: 16, marginRight: 5 }} />
            ) : null}
            <TextWidget>{item.DisplayName}</TextWidget>
          </div>
        ),
        value: item.OutId,
        menu: item,
        children: transferData(item.Children, item.Route),
      });
    });
    $menuTree(tree);
  }, []);

  // 关闭侧滑菜单
  const closeMenu = useCallback(() => {
    $visible(false);
  }, []);

  // 设置当前路由节点值为菜单树默认值
  const getDefaultValue = useCallback(
    (menuTree: any[]) => {
      let selecteds: string[] = [];
      menuTree.map((item: any) => {
        if (
          item.menu.Route === params.pageRouter ||
          (params.pageRouter === 'page' && item.menu.Route === params.childRouter)
        ) {
          selecteds.push(item.value);
        }
        if (Array.isArray(item.children) && item.children.length) {
          item.children.map((val: any) => {
            if (
              val.menu.oldRoute === params.pageRouter ||
              val.menu.oldRoute === params.childRouter
            ) {
              if (!selecteds.length) {
                selecteds.push(item.value);
              }
              selecteds.push(val.value);
            }
          });
        }
      });
      $defaultValue(selecteds);
    },
    [params],
  );

  return (
    <div
      className={`inbiz-popup-menu ${className}`}
      style={{
        height: '100%',
      }}
    >
      <>
        <Button
          style={{
            backgroundColor: bgColor,
            border: 'none',
            height: 34,
            display: 'flex',
            alignItems: 'center',
          }}
          onClick={() => {
            $visible(true);
            getDefaultValue(menuTree);
          }}
        >
          <Space align="center">
            {type && <InbizIcon type={type} style={{ color, fontSize: size }} />}
            {status && (
              <span style={{ color: textColor, fontSize }}>
                <TextWidget>{value}</TextWidget>
              </span>
            )}
          </Space>
        </Button>

        <Popup
          visible={visible}
          onMaskClick={closeMenu}
          position={position ? position : 'left'}
          bodyStyle={{ width: '70vw' }}
          bodyClassName="inbiz-popup-menu-body"
          destroyOnClose
        >
          <TreeSelect
            options={menuTree}
            defaultValue={defaultValue}
            onChange={(value, nodes) => {
              let option = nodes.options;
              let menu = option[option.length - 1].menu;
              Core.handleClick(menu, history, () => {
                closeMenu();
              });
            }}
          />
        </Popup>
      </>
    </div>
  );
};

export default PopupMenu;